import { EventEmitter, IEventListener } from '../../engine/common/event-emmiter';
import { CanvasModel } from '../models/canvas.model';
import { CanvasView } from '../views/canvas.view';
import { Controller } from './controller';

export class CanvasController extends Controller {
  #isStarted = false;
  #listeners: IEventListener[] = [];

  model = new CanvasModel();
  view = new CanvasView();

  onCanvasReady = new EventEmitter<HTMLCanvasElement>();

  start() {
    if (this.#isStarted) {
      throw new Error('Canvas controller is already started');
    }

    this.#isStarted = true;

    this.#listeners.push(this.model.onStateChanged.listen(() => this.renderView()));
    this.#listeners.push(this.view.onAnyKeyPressed.listen(() => this.model.pressAnyKey()));
    this.#listeners.push(this.view.onCanvasReady.listen((canvasElement) => this.onCanvasReady.emit(canvasElement)));

    this.view.listenToEvents();
    this.model.start();
  }

  changeLoading(isLoading: boolean) {
    this.model.changeLoading(isLoading);
  }

  finish(isVictorious: boolean) {
    this.model.finish(isVictorious);
    this.#listeners.forEach((listener) => listener.dispose());
  }

  private renderView() {
    if (this.model.isVictorious !== null) {
      if (this.model.isVictorious) {
        this.view.renderVictory();
      } else {
        this.view.renderDefeat();
      }

      return;
    }

    if (this.model.isAnyKeyPressed) {
      this.view.renderCanvas(this.model.isLoading);
    } else {
      this.view.renderHello();
    }
  }
}
